package com.tust.app.util;

import com.tust.app.domain.FileEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class FileUploadTool {

    public FileEntity createFile(MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        FileEntity entity = new FileEntity();

        // 获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件保存路径
        String savePath = request.getSession().getServletContext().getRealPath("/uploadedFiles/");
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        // 使用原始文件名保存文件
        File saveFile = new File(saveDir, originalFilename);
        multipartFile.transferTo(saveFile);

        // 设置 FileEntity 属性
        entity.setTitleOrig(originalFilename);
        entity.setTitleAlter(originalFilename); // 保持文件名不变
        entity.setSize(multipartFile.getSize() + " bytes");
        entity.setType(multipartFile.getContentType());
        entity.setPath(saveFile.getAbsolutePath());
        entity.setUploadTime(new Date());

        return entity;
    }

}